/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package eu.fastl.dragster.loadgen.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VariableSubstituter {
    private static final Logger LOGGER = LoggerFactory.getLogger(VariableSubstituter.class);
    private static final String VAR_START = "${";
    private static final String VAR_END = "}";

    public String substituteVariables(String line) {
        if (line.contains(VAR_START)) {
            StringBuilder retval = new StringBuilder();
            String substringBeforeStart = StringUtils.substringBefore(line, VAR_START);

            if (substringBeforeStart.contains(VAR_END)) {
                LOGGER.warn("Missing " + VAR_START + " in URL:" + line);
                return line;
            }

            retval.append(substringBeforeStart);

            String substringAfterStart = StringUtils.substringAfter(line, VAR_START);
            if (!substringAfterStart.contains(VAR_END)) {
                LOGGER.warn("Missing " + VAR_END + " in URL:" + line);
                return line;
            }

            String variableName = StringUtils.substringBefore(substringAfterStart, VAR_END);
            String variableValue = System.getProperty(variableName);
            if (variableValue == null) {
                throw new IllegalArgumentException("Missing variable:" + variableName + " in url " + line);
            }
            retval.append(variableValue);

            String substringAfterEnd = StringUtils.substringAfter(line, VAR_END);
            retval.append(substringAfterEnd);
            return substituteVariables(retval.toString());
        } else if (line.contains(VAR_END)) {
            LOGGER.warn("Missing " + VAR_START + " in URL:" + line);
            return line;
        }
        return line;
    }
}
